package cn.csg.ams.collect2.poptopics.redisPool;

import cn.csg.ams.collect2.poptopics.datahub.TupleRecordDataUtils;
import cn.csg.ams.collect2.poptopics.entity.LoadData;
import cn.csg.ams.collect2.poptopics.infrastructure.utils.JsonUtil;
import cn.csg.ams.collect2.poptopics.infrastructure.utils.DateUtil;
import com.aliyun.datahub.client.model.TupleRecordData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 电能表最新的电流电压池
 */
@Component
public class LatestCurrVoltPool {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 运行电能表最新电流电压key
     */
    public static final String LATEST_CURR_VOLT_KEY = "latest_curr_volt_";


    /**
     * 更新最新电流电压
     */
    public void updateLatestCurrVolt(TupleRecordData data) {
        // 运行电能表标识
        Object runMeterId = data.getField(0);
        // 数据时间
        String dateTimeStr = TupleRecordDataUtils.getStringField(data, 10);
        Date dateTime = DateUtil.parse(dateTimeStr, "yyyyMMddHHmmss");
        // key
        String key = LATEST_CURR_VOLT_KEY + runMeterId;


        LoadData preLoadData = JsonUtil.toObject(redisTemplate.opsForValue().get(key), LoadData.class);
        if (preLoadData != null && dateTime != null && preLoadData.getDataTime().getTime() < dateTime.getTime()) {
            // 该条数据时间小于redis中的时间，不用更新
            return;
        }

        // A相电压
        BigDecimal voltA = TupleRecordDataUtils.getBigDecimalField(data, "p_volt_a");
        // A相电压
        BigDecimal voltB = TupleRecordDataUtils.getBigDecimalField(data, "p_volt_b");
        // A相电压
        BigDecimal voltC = TupleRecordDataUtils.getBigDecimalField(data, "p_volt_c");
        // A相电流
        BigDecimal currA = TupleRecordDataUtils.getBigDecimalField(data, "p_curr_a");
        // A相电流
        BigDecimal currB = TupleRecordDataUtils.getBigDecimalField(data, "p_curr_b");
        // A相电流
        BigDecimal currC = TupleRecordDataUtils.getBigDecimalField(data, "p_curr_c");

        // value
        LoadData loadData = new LoadData();
        loadData.setRunMeterId(runMeterId.toString());
        loadData.setDataTime(dateTime);
        loadData.setVoltA(voltA);
        loadData.setVoltB(voltB);
        loadData.setVoltC(voltC);
        loadData.setCurrA(currA);
        loadData.setCurrB(currB);
        loadData.setCurrC(currC);
        String value = JsonUtil.toJson(loadData);
        // 更新redis中的该电能表的最新电流电压
        redisTemplate.opsForValue().set(key, value);
    }

}
